package com.duke.payphone.acct;

import java.io.Serializable;
import java.util.Map;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.duke.payphone.Global;
import com.duke.payphone.LoginActivity;
import com.duke.payphone.R;
import com.duke.payphone.ServerPortal;
import com.duke.payphone.factory.MapFactory;


/**
 * note: each credit card will have a unique nickname; unique key(username,
 * nickname) for credit card table
 * 
 * 
 * @author Michael
 * 
 */
public class CreditNewActivity extends Activity {

    private Global globalvars;

    private EditText cardnum;
    private EditText exp;
    private EditText name;
    private EditText add1;
    private EditText add2;
    private EditText city;
    private EditText state;
    private EditText zip;

    private String cardnumStr;
    private String expStr;
    private String nameStr;
    private String add1Str;
    private String add2Str;
    private String cityStr;
    private String stateStr;
    private String zipStr;

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_credit_new);

        globalvars = (Global) getApplicationContext();

        cardnum = (EditText) findViewById(R.id.et_cardnum);
        exp = (EditText) findViewById(R.id.et_exp);
        name = (EditText) findViewById(R.id.et_name);
        add1 = (EditText) findViewById(R.id.et_add1);
        add2 = (EditText) findViewById(R.id.et_add2);
        city = (EditText) findViewById(R.id.et_city);
        state = (EditText) findViewById(R.id.et_state);
        zip = (EditText) findViewById(R.id.et_zip);

    }

    @Override
    public boolean onCreateOptionsMenu (Menu menu) {
        // getMenuInflater().inflate(R.menu.activity_credit_new, menu);
        // return true;
        return false;
    }

    public void executeBack (View v) {
        finish();
    }

    public void executeAddCard (View v) {
        updateData();

        // check validity
        if (checkData()) {

            // send to server
            Map<String, Serializable> response = ServerPortal.contactServer(prepareTransmitMap());

            // wait for reply
            if (response.containsKey("server") && response.get("server").equals("valid")) {

                if (response.containsKey("session") && response.get("session").equals("valid")) {

                    if (response.containsKey("result") && response.get("result").equals("valid")) {
                        onNewCardValid(response);
                    }
                    else {
                        onNewCardInvalid(response);
                    }
                }
                else {
                    onSessionInvalid();
                }
            }
            else {
                onServerInvalid();
            }
        }

    }

    /**
     * Rereads the data from text fields
     */
    private void updateData () {
        cardnumStr = cardnum.getText().toString();
        expStr = exp.getText().toString();
        nameStr = name.getText().toString();
        add1Str = add1.getText().toString();
        add2Str = add2.getText().toString();
        cityStr = city.getText().toString();
        stateStr = state.getText().toString();
        zipStr = zip.getText().toString();
    }

    /**
     * returns a map
     * 
     * @return
     */
    private Map<String, Serializable> prepareTransmitMap () {
        Map<String, Serializable> request = MapFactory.createTransmitMap("newcard");
        request.put("cardnumber", cardnumStr);
        request.put("expdate", expStr);
        request.put("name", nameStr);
        request.put("address1", add1Str);
        request.put("address2", add2Str);
        request.put("city", cityStr);
        request.put("state", stateStr);
        request.put("zip", zipStr);
        return request;
    }

    private boolean checkData () {
        // verify data is correct
        if (cardnumStr.isEmpty() || expStr.isEmpty() || nameStr.isEmpty() || add1Str.isEmpty() ||
            cityStr.isEmpty() || stateStr.isEmpty() || zipStr.isEmpty()) {
            // if incorrect, toast: [how to correct the data]
            Toast.makeText(globalvars, "All fields are required.", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    /**
     * @param response
     */
    private void onNewCardValid (Map<String, Serializable> response) {

        Toast.makeText(globalvars, "New card added successfully.", Toast.LENGTH_SHORT).show();

        // go back to card list
        finish();
    }

    /**
     * @param response
     */
    private void onNewCardInvalid (Map<String, Serializable> response) {
        Toast.makeText(globalvars, "Could not add new card. Please try again.", Toast.LENGTH_SHORT)
                .show();
    }

    /**
     * If server has timed out
     */
    private void onServerInvalid () {
        // toast: server error, please verify server connection and retry
        Toast.makeText(globalvars, "Server/network error. Please retry.", Toast.LENGTH_SHORT)
                .show();
    }

    /**
     * If session has timed out
     */
    private void onSessionInvalid () {
        // reset the sessionID to null
        Global.sessionid = "";

        // toast: current session has timed out
        Toast.makeText(globalvars, "Current session has timed out.", Toast.LENGTH_SHORT).show();

        // go back to the login screen
        Intent toLogin = new Intent(this, LoginActivity.class);
        toLogin.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(toLogin);
        finish();
    }

}
